package c.x.jy.wexin.controller;

import c.x.jy.bean.event.*;
import c.x.jy.common.annotation.IntoSet;
import c.x.jy.common.annotation.Login;
import c.x.jy.common.annotation.NoRepeatSubmit;
import c.x.jy.common.utils.PageUtils;
import c.x.jy.common.utils.R;
import c.x.jy.common.utils.SysUtils;
import c.x.jy.dao.dto.OrderEntityDto;
import c.x.jy.dao.dto.TeacherEntityDto;
import c.x.jy.dao.entity.*;
import c.x.jy.dao.model.OrderForm;
import c.x.jy.service.config.BusinessConfigService;
import c.x.jy.service.config.WechatConfigService;
import c.x.jy.service.pay.PayService;
import c.x.jy.service.redis.Cache;
import c.x.jy.service.redis.RedisConstant;
import c.x.jy.service.service.*;
import c.x.jy.service.utils.wechat.WechatCommonUtil;
import c.x.jy.service.utils.wechat.WechatConfig;
import c.x.jy.wexin.utils.HttpContextUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.PrintWriter;
import java.math.BigDecimal;
import java.util.*;


/**
 * 会员订单表
 *
 * @author amwhyh
 * @email xxx@xx.com
 * @date 2021-05-25 10:49:13
 */
@Slf4j
@Controller
@RequestMapping("wechat/order")
public class OrderController   {
    @Autowired
    private OrderService orderService;
    @Autowired
    private MemberService customerService;
    @Autowired
    private TeacherService teacherService;
    @Autowired
    private PayService payService;
    @Autowired
    private WechatConfigService wechatConfigService;
    @Autowired
    private OrderBillService orderBillService;
    @Autowired
    private Cache redisUtils;
    @Autowired
    private OrderAwnserService orderAwnserService;
    
	@Autowired
	private OrderItemsService orderItemsService;

    @Autowired
    private BusinessConfigService businessConfigService;
    @Autowired
    private	BusinessService 	businessService;
    @Autowired
    private MemberWalletService memberWalletService;
    /**
     *
     * 列表
     */
    @ResponseBody
    @Login
    @RequestMapping("/list")
    @IntoSet(Includefields={"teacherHeadimgurl","teacherName","goods","teacherMemberId"})
    public R list(@RequestParam Map<String, Object> params){
        params.put("memberId",   customerService.getCurrUser().getId());
        PageUtils page = orderService.queryPage(params);

        return R.put(page);
    }
    /**
     * 列表
     */
    @ResponseBody
    @Login
    @RequestMapping("/teacherlist")
    @IntoSet(Includefields={"headimgurl","memberName","goods","memberHeadimgurl"})
    public R teacherlist(@RequestParam Map<String, Object> params){
//        params.put("memberId",   customerService.getCurrUser().getId());
        Long memberId = customerService.getCurrUser().getId();
        TeacherEntity teacherEntity = teacherService.getByMemberId(memberId);
        Long teacherId = teacherEntity.getId();
        params.put("teacherId",   teacherId);
        PageUtils page = orderService.queryPage(params);

        return R.put(page);
    }
    /**
     * 列表
     */
    @ResponseBody
    @Login
    @RequestMapping("/newquickask")
    @IntoSet(Includefields={"goods","memberHeadimgurl","memberName"})
    public R newquickask(@RequestParam Map<String, Object> params){
        PageUtils page = orderService.newquickask(params);

        return R.put(page);
    }
    /**
     * 抢单
     */
    @ResponseBody
    @Login
    @RequestMapping("/roborder")
    public R roborder(Long orderId){

        OrderEntity orderEntity = orderService.selectOrderBYIdForUpdate(orderId);
        if(orderEntity.getTeacherId()!=null&&orderEntity.getTeacherId()>0) {
        	return R.error("订单已经 被人抢走了！");
        }
        Long memberId = customerService.getCurrUser().getId();
        TeacherEntity teacherEntity = teacherService.getByMemberId(memberId);
        Long teacherId = teacherEntity.getId();
        orderEntity.setTeacherId(teacherId);
        if((orderEntity.getServiceType()==2)&&((orderEntity.getStatus()==4)||(orderEntity.getStatus()==0))){
            orderEntity.setStatus(1);

            //抢单成功，发送消息给下单人
            BusinessEntity business=  businessService.getById( orderEntity.getBusinessId());
            String templateId=businessConfigService.getBusinessConfigValue(null, "GZH_NOTE_TEMPLATE");
            String url="wechat/topage?page=page/order/orderlist/orderlist&bcode="+business.getCode();
            TeacherEntityDto teacher=		teacherService.selectById(teacherId);
            List<String> listmsg=new ArrayList<>();

            listmsg.add("订单服务进度通知");
            listmsg.add( "您的闪测订单已被大师："+teacher.getName()+"接单!"  );

            List<OrderItemsEntity> list = orderItemsService.selectListByOrderNo(orderEntity.getId());

            listmsg.add(orderEntity.getOrderNo());
            listmsg.add(list.get(0).getItemName());
            listmsg.add(list.get(0).getDescription());

            EventPublisher.publishEvent(new WxTemplateMsgEvent(this,  customerService.getById(orderEntity.getMemberId()).getOpenid(),templateId,url,listmsg));



        }else{
            return R.error("订单有误");
        }


        orderService.updateById(orderEntity);
        
        
        OrderBillEntity order = orderBillService.selectByOrderNo(orderEntity.getOrderNo());
        
    	List <OrderItemsEntity> list=     	orderItemsService.selectListByOrderNo(orderEntity.getId());
    	orderEntity.setItemlist(list);
    	orderEntity.setOrderBill(order);
		OrderCommissionEvent oc=new OrderCommissionEvent(this,orderEntity);
		EventPublisher.publishEvent(oc);




        return R.ok();
    }
    /**
     *生成订单
     * type :订单类型，1-咨询订单，2-闪测订单，3-提问订单，4-充值订单
     */
    @ResponseBody
    @NoRepeatSubmit
    @Login
    @RequestMapping(value = "/createOrder" ,method = RequestMethod.POST)
    public R createOrder(@RequestBody OrderForm orderfrm){
        return  R.put( orderService.saveNewOrder(orderfrm));
    }
    /**
     * 下单
     */
    @ResponseBody
    @NoRepeatSubmit
    @Login
    @RequestMapping(value = "/pay" ,method = RequestMethod.POST)
    public R pay(  String  orderNo){
        OrderBillEntity orderBillEntity= orderBillService.selectByOrderNo(orderNo);

        Map map=   payService.wechatPrePay(orderNo,orderNo,orderBillEntity.getDiscountPrice(),orderBillEntity.getCommont(), HttpContextUtils.getRequestIP(),	customerService.getCurrUser().getOpenid(), wechatConfigService.getDefultConfing());
        return  R.put( map);
    }

    /**
     * 使用余额支付，下单
     */
    @Transactional
    @ResponseBody
    @NoRepeatSubmit
    @Login
    @RequestMapping(value = "/balancepay" ,method = RequestMethod.POST)
    public R balancepay(  String  orderNo)throws Exception {
        OrderBillEntity orderBillEntity= orderBillService.selectByOrderNo(orderNo);

        //判断是否咨询订单，不是的，退出
        OrderEntity o = orderService.selectOrderByNo(orderNo);
        if(!o.getServiceType().equals(1)&&!o.getServiceType().equals(2)&&!o.getServiceType().equals(5)){
            return R.error("当前仅咨询订单、闪测订单、VIP开通支持余额支付");
        }
        //扣余额
        MemberWalletEntity memberWalletEntity = memberWalletService.getByCurUser();
        BigDecimal balance = memberWalletEntity.getBalance().subtract(orderBillEntity.getDiscountPrice());
        if(balance.compareTo(new BigDecimal(0))==-1){
            return R.error("支付异常，余额不足");
        }
        memberWalletEntity.setBalance(balance);
        memberWalletService.updateById(memberWalletEntity);


        Map<String, Object> map = new HashMap<String, Object>();
        map.put("transaction_id", SysUtils.generateCode());
        map.put("cash_fee",orderBillEntity.getDiscountPrice().multiply(new BigDecimal(100)));
        map.put("serviceType",o.getServiceType());
        BalancePayDoneEvent balancePayDoneEvent = new c.x.jy.bean.event.BalancePayDoneEvent(this, orderBillEntity, map);
        EventPublisher.publishEvent(balancePayDoneEvent);
        //Map map=   payService.wechatPrePay(orderNo,orderNo,orderBillEntity.getDiscountPrice(),orderBillEntity.getCommont(), HttpContextUtils.getRequestIP(),	customerService.getCurrUser().getOpenid(), wechatConfigService.getDefultConfing());
        return  R.put( map);
    }

    /**
     * 支付回调
     */
    @RequestMapping(value = "notify")
    public void updateOrderBySerialNumber(HttpServletRequest request, HttpServletResponse httpServletResponse)
            throws Exception {
        String inputLine = "";
        String notityXml = "";
        while ((inputLine = request.getReader().readLine()) != null) {
            notityXml += inputLine;
        }
        Map<String, Object> map = new HashMap<String, Object>();
        map = WechatCommonUtil.getMapFromXML(notityXml);
        log.info("微信支付回调：" + map.toString());
        SortedMap<String, Object> smap = new TreeMap<>(map);

        String orderNumber = map.get("out_trade_no").toString();

        String paying = redisUtils.get("data", orderNumber);
        PrintWriter writer = httpServletResponse.getWriter();

        WechatConfig userConfig = wechatConfigService.getDefultConfing();
        if (!WechatCommonUtil.isWechatSign(smap, userConfig.getApiKey())) {
            log.error("支付回调验签失败,参数:{}", notityXml);
            writer.print(
                    "<xml><return_code><![CDATA[FAIL]]></return_code><return_msg><![CDATA[NO]]></return_msg></xml>");
            return;
        }

        if (map.get("result_code").toString().equals("SUCCESS") && paying == null) {
            log.debug("支付成功！");
            //OrderPayEntity order = orderPayService.selectByNo(orderNumber);
             OrderBillEntity order=   orderBillService.selectByOrderNo(orderNumber);
            if (order == null) {
                log.error("支付回调找不到该订单:{}", orderNumber);
                return;
            }
            redisUtils.set("data", orderNumber, RedisConstant.DEFAULT_EXPIRE.longValue());
            OrderDoneEvent orderDoneEvent = new c.x.jy.bean.event.OrderDoneEvent(this, order, map);
            EventPublisher.publishEvent(orderDoneEvent);
            // orderService.updateByPaySuccess(orderNumber,
            // map.get("transaction_id").toString(),Integer.valueOf((String)
            // map.get("cash_fee")));
            writer.print(  "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
            // return
            // "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>";
            return;
        }
        writer.print( "<xml><return_code><![CDATA[SUCCESS]]></return_code><return_msg><![CDATA[OK]]></return_msg></xml>");
    }

    /**
     * 信息
     */
    @Login
    @ResponseBody
    @RequestMapping("/info/{id}")
    public R info(@PathVariable("id") Long id){
		OrderEntity order = orderService.getById(id);

        return R.put(order);
    }
    /**
     * 信息
     */
    @Login
    @ResponseBody
    @RequestMapping("/infodto/{id}")
    @IntoSet(Includefields={"goods","memberHeadimgurl","memberName"})
    public R infodto(@PathVariable("id") Long id){
        OrderEntityDto order = orderService.infodto(id);

        return R.put(order);
    }

    @Login
    @ResponseBody
    @RequestMapping("/finishorder")
    public R finishorder(Long orderId){
        OrderEntity orderEntity;

        if(orderId==null)
            return R.error("订单号错误");
        orderEntity = orderService.getById(orderId);
        List<OrderAwnserEntity> awnserList = orderAwnserService.getByOrderId(orderId);
        if(orderEntity.getServiceType().equals(2)&&awnserList.size()<=0)
            return R.error("闪测订单没有沟通记录，不能结束");

        orderEntity.setStatus(2);
        orderService.updateById(orderEntity);
        return R.put(orderEntity);
    }

    @Login
    @ResponseBody
    @RequestMapping("/removePay")
    public R removePay(String  orderNo) {
        orderService.removePay(orderNo);
        return R.ok();

    }

    @Login
    @ResponseBody
    @RequestMapping(value = "/deleteorder",method = RequestMethod.DELETE)
    public R deleteorder(Long orderId){
        OrderEntity orderEntity;

        if(orderId==null)
            return R.error("订单号错误");
        orderEntity = orderService.getById(orderId);
        Long memberId = customerService.getCurrUser().getId();
        if(!memberId.equals(orderEntity.getMemberId()))
            return  R.error("非本订单用户");
        if(!orderEntity.getStatus().equals(0)){
            return  R.error("订单状态错误");
        }
        orderService.removeById(orderEntity);

        return R.ok();
    }
    /**
     * 保存
//     */
//    @Login
//    @RequestMapping("/save")
//    public R save(@RequestBody OrderEntity order){
//		orderService.save(order);
//
//        return R.ok();
//    }

    /**
     * 修改
     */
//    @RequestMapping("/update")
//    public R update(@RequestBody OrderEntity order){
//		orderService.updateById(order);
//
//        return R.ok();
//    }

    /**
     * 删除
     */
//    @RequestMapping(value = "/delete/{id}",method =RequestMethod.DELETE )
//    public R delete(@PathVariable("id") Long id){
//		orderService.removeByIds(Arrays.asList(id));
//
//        return R.ok();
//    }

}

